package com.vote.web.controller.business;

import com.vote.business.domain.VoteInfo;
import com.vote.business.domain.VoteOption;
import com.vote.business.domain.vo.UserVoteRecordVO;
import com.vote.business.domain.vo.VoteInfoVO;
import com.vote.business.domain.vo.VoteOptionWithTitleVO;
import com.vote.business.service.IUserVoteRecordService;
import com.vote.business.service.IVoteInfoService;
import com.vote.business.service.IVoteOptionService;
import com.vote.common.annotation.Log;
import com.vote.common.core.controller.BaseController;
import com.vote.common.core.domain.AjaxResult;
import com.vote.common.core.domain.entity.SysRole;
import com.vote.common.core.domain.entity.SysUser;
import com.vote.common.core.domain.model.LoginUser;
import com.vote.common.core.page.TableDataInfo;
import com.vote.common.enums.BusinessType;
import com.vote.common.utils.SecurityUtils;
import com.vote.common.utils.poi.ExcelUtil;
import com.vote.system.service.ISysRoleService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 投票信息Controller
 * 
 * @author ruoyi
 * @date 2025-07-14
 */
@RestController
@RequestMapping("/business/voteInfo")
public class VoteInfoController extends BaseController
{
    @Autowired
    private IVoteInfoService voteInfoService;

    @Autowired
    private IVoteOptionService voteOptionService;

    @Autowired
    private IUserVoteRecordService userVoteRecordService;

    @Autowired
    private ISysRoleService roleService;
    /**
     * 查询投票信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:voteInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(VoteInfo voteInfo)
    {
        startPage();
        SysRole defaultRole = roleService.selectRoleByRoleKey("admin");
        if (defaultRole == null) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SysUser user = loginUser.getUser();
            voteInfo.setUserId(user.getUserId());
        }
        List<VoteInfo> list = voteInfoService.selectVoteInfoList(voteInfo);
        return getDataTable(list);
    }
    /**
     * 查询投票信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:voteInfo:list')")
    @GetMapping("/front/list")
    public TableDataInfo frontList(VoteInfo voteInfo)
    {
        startPage();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        voteInfo.setUserId(user.getUserId());
        List<VoteInfo> list = voteInfoService.selectVoteInfoList(voteInfo);
        return getDataTable(list);
    }
    /**
     * 查询用户投票信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:voteInfo:list')")
    @GetMapping("/userList")
    public TableDataInfo list(VoteInfoVO voteInfoVO)
    {
        startPage();
//         直接获取当前登录用户ID（自动解析请求头中的Token）
//         1. 从Security上下文获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        voteInfoVO.setUserId(user.getUserId());
        List<VoteInfoVO> list = voteInfoService.selectUserVoteList(voteInfoVO);
        return getDataTable(list);
    }
    /**
     * 导出投票信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:voteInfo:export')")
    @Log(title = "投票信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, VoteInfo voteInfo)
    {
        List<VoteInfo> list = voteInfoService.selectVoteInfoList(voteInfo);
        ExcelUtil<VoteInfo> util = new ExcelUtil<VoteInfo>(VoteInfo.class);
        util.exportExcel(response, list, "投票信息数据");
    }

    /**
     * 获取投票信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:voteInfo:query')")
    @GetMapping(value = "/{voteId}")
    public AjaxResult getInfo(@PathVariable("voteId") Long voteId)
    {
        return success(voteInfoService.selectVoteInfoByVoteId(voteId));
    }

    /**
     * 新增投票信息
     */
    @PreAuthorize("@ss.hasPermi('business:voteInfo:add')")
    @Log(title = "投票信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody VoteInfo voteInfo)
    {
        return toAjax(voteInfoService.insertVoteInfo(voteInfo));
    }

    /**
     * 修改投票信息
     */
    @PreAuthorize("@ss.hasPermi('business:voteInfo:edit')")
    @Log(title = "投票信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody VoteInfo voteInfo)
    {
        return toAjax(voteInfoService.updateVoteInfo(voteInfo));
    }

    /**
     * 更新投票信息状态
     */
    @PreAuthorize("@ss.hasPermi('business:voteInfo:edit')")
    @Log(title = "投票信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updateVoteInfoStatus")
    public AjaxResult updateVoteInfoStatus(@RequestBody VoteInfo voteInfo)
    {
        VoteOptionWithTitleVO vo=new VoteOptionWithTitleVO();
        vo.setVoteId(voteInfo.getVoteId());
        List<VoteOptionWithTitleVO> voteOptionWithTitleVOSes=voteOptionService.selectVoteOptionWithTitleDTOList(vo);
            if(voteOptionWithTitleVOSes.isEmpty()){
                return AjaxResult.error("请先添加投票选项");
            }

        return toAjax(voteInfoService.updateVoteInfoStatus(voteInfo));
    }

    /**
     * 删除投票信息
     */
    @PreAuthorize("@ss.hasPermi('business:voteInfo:remove')")
    @Log(title = "投票信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{voteIds}")
    public AjaxResult remove(@PathVariable Long[] voteIds)
    {
        return toAjax(voteInfoService.deleteVoteInfoByVoteIds(voteIds));
    }
    @PreAuthorize("@ss.hasPermi('business:voteInfo:query')")
    @GetMapping(value = "/front/{voteId}")
    public AjaxResult getVoteResult(@PathVariable("voteId") Long voteId){
        VoteInfo voteInfo=voteInfoService.selectVoteInfoByVoteId(voteId);
        VoteOption voteOption=new VoteOption();
        voteOption.setVoteId(voteId);
        voteInfo.setVoteOptions(voteOptionService.selectVoteOptionList(voteOption));
        voteInfo.setParticipantCount(userVoteRecordService.selectParticipantCount(voteId));
        voteInfo.setVoteCount(userVoteRecordService.selectTotalVotes(voteId));

        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        UserVoteRecordVO r=new UserVoteRecordVO();
        r.setUserId(user.getUserId());
        r.setVoteId(voteId);
        UserVoteRecordVO userVoteRecordVO=userVoteRecordService.selectUserVoteRecordDtoByUId(r);
        voteInfo.setOptionContent(userVoteRecordVO.getOptionContent());
        return success(voteInfo);
    }
}
